# 2020.10.20 来自头条优特课堂
from dataclasses import dataclass
from flask import Blueprint, request, render_template, redirect, url_for, session, g, jsonify

login_blue = Blueprint('login_blue', __name__, static_url_path='/', template_folder='templates', static_folder='static')


# app = Flask(__name__, static_url_path='/')
# app.debug = True
# app.config['SECRET_KEY'] = 'askl;dfj;aksdjf;safjk235'
# from login import login_blue


@dataclass
class User:
    id: int
    username: str
    password: str


users = [
    User(1, 'Admin', '123456'),
    User(2, 'Eason', '888888'),
    User(3, 'Runler', '666666'),
]


@login_blue.before_request
def before_request():
    if 'user_id' in session:
        user = [u for u in users if u.id == int(session['user_id'])][0]
        g.user = user
    else:
        g.user = None


@login_blue.route('/', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        # 登陆操作
        session.pop('user_id', None)  # 清空操作
        username = request.form.get("username", None)
        password = request.form.get("password", None)
        user = [u for u in users if u.username == username]
        if len(user) > 0:
            user = user[0]
        if user and user.password == password:
            session['user_id'] = user.id
            return redirect(url_for('login_blue.profile'))
    return render_template("login.html")


@login_blue.route('/profile')
def profile():
    if not g.user:
        return redirect(url_for('login_blue.login'))  # url_for() 参数为endpoint, 为路由视图定义的def xxx 名

    return render_template('profile.html')


@login_blue.route('/reguser/', methods=['GET', 'POST'])
def reg_user():
    if request.method == 'POST':  # request.is_xhr
        name = request.form.get('username', None)
        return '用户：' + name + ' 已注册成功！'
        # return jsonify(name)
    return render_template('reg-user.html')


@login_blue.route('/checkuser/')
def check_user():
    """校验可注册的用户名"""
    name = request.args.get('username', None)
    user = [u for u in users if u.username.lower() == name.lower()]
    if len(user) > 0:
        return jsonify(False)
    else:
        return jsonify(True)

# if __name__ == "__main__":
#     app.run()
